package singleton;

import java.io.Serializable;

/**
 * 双重校验锁的单例
 *
 * 目的: 解决线程安全带来的时间开销
 * 实现:
 * 1. 同步锁应当只在未创建实例时使用
 * 2. 未实例化使用synchronized
 * 
 * @author insight 
 * @since 2021/4/22
 */
public class SerialSingletonDoubleCheck implements Serializable {
    /**
     * new 不是原子性操作
     * volatile避免指令重排 防止instance未完全实例化
     */
    private static volatile SerialSingletonDoubleCheck instance;

    private SerialSingletonDoubleCheck() {
        System.out.println("SingletonDoubleCheck is Instantiated!");
    }

    public static SerialSingletonDoubleCheck getInstance() {
        if (instance == null) {
            synchronized (SerialSingletonDoubleCheck.class) {
                if (instance == null) {
                    instance = new SerialSingletonDoubleCheck();
                }
            }
        }
        return instance;
    }
}